from datetime import datetime
from django.utils import timezone
from django.utils.timezone import now

from django.core.mail import send_mail
from django.http import HttpResponse
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.template import loader
from .models import *
from django.db.models import Q
from django.views.decorators.http import require_http_methods


# Create your views here.


# 自定义一个用户登录校验装饰器
def checklogin(func):
    def check(request, *args):
        # 获取session 8uhb v  信息
        username = request.session.get('username')
        if username:
            return func(request, *args)
        else:
            return redirect(reverse('xzblogin'))
    return check


# @checklogin
def index(req):
    # 获取资源信息
    rlist = Resource.objects.all()
    print(rlist)
    # 热门资源
    hotList = Resource.objects.filter(type=1)[0:12]
    # 精品资源
    boutList = Resource.objects.filter(type=2)[0:12]
    context = {'hotList': hotList, 'boutList': boutList}
    return render(req, 'xzb/index.html', context)


def upload(req):
    if req.method == 'GET':
        username = req.session.get('user_name')
        print('session:username:', username)
        return render(req, 'xzb/upload.html')
    elif req.method == 'POST':
        # 上传提交
        # files = req.FILES.getlist('resource')
        # for file in files:
            # 获取文件的名称
            # filename = 'media/upload/' + file.name
            # with open(filename, 'wb') as fp:
            #     fp.write(file.read())
            # 边读边写
            # for chunk in file.chunks():
            #     with open(filename, 'wb') as fp:
            #         fp.write(chunk)
        # file = FileInfo()
        # file.fileName = req.POST.get('resourceName')
        # file.fileUrl = req.FILES.get('resource')
        # file.save()
        r = Resource()
        r.resourceName = req.POST.get('resourceName')
        r.resourceUrl = req.FILES.get('resource')
        r.resourceSize = req.FILES.get('resource').size
        r.remark = req.POST.get('remark')
        r.keyword = req.POST.get('keyword')
        r.resourceType = req.POST.get('resourceType')
        r.score = req.POST.get('score')
        username = req.session.get('username')
        user = User.objects.get(userName=username)
        if user:
            r.userId = user.id
        else:
            r.userId = 1
        r.delFlag = 0  # 未删除
        r.status = 0  # 0未审核  1审核
        r.Create_time = datetime.now()
        r.Update_time = datetime.now()
        r.save()
        return redirect(reverse('xzbindex'))


def shoucang(req):
    return render(req, 'xzb/shoucang.html')


def register(req):
    if req.method == 'GET':
        return render(req, 'xzb/register.html')
    elif req.method == 'POST':
        # 获取页面提交的字段
        username = req.POST.get('username')
        password = req.POST.get('password')
        email = req.POST.get('email')
        phone = req.POST.get('phone')
        user = User()
        user.userName = username
        user.password = password
        user.email = email
        user.phone = phone
        user.create_time = datetime.now()
        user.update_time = datetime.now()
        user.save()
        # return HttpResponse('注册成功')
        context = {'user': user}
        return render(req, 'xzb/next_reg.html', context)


def login(req):
    if req.method == 'GET':
        return render(req, 'xzb/login.html')
    else:
        # 获取表单数据，进行登录校验
        username = req.POST.get('username')
        password = req.POST.get('password')
        rememberme = req.POST.get('rememberme')
        print('rememberme', rememberme)
        # 多条件查询， 或语句
        user = User.objects.filter((Q(userName__iexact=username) & Q(password__iexact=password) & Q(status__iexact=1)) |
                                   (Q(phone__iexact=username) & Q(password__iexact=password)& Q(status__iexact=1)) |
                                   (Q(email__iexact=username) & Q(password__iexact=password)& Q(status__iexact=1)))
        print(user.query)
        if user:
            # cookie = req.COOKIES
            # res = render(req, 'xzb/index.html', {'cookie': cookie})
            # res = render(req, 'xzb/index.html')
            # 设置session信息
            req.session['username'] = username
            req.session['password'] = password
            # 设置有效期为七天
            req.session.set_expiry(7*24*60*60)
            # 获取session信息
            # print('session', req.session.get('user_name'))
            # print('session', req.session.get('pass_word'))
            # 清除session
            # req.session.clear()

            res = redirect(reverse('xzbindex'))
            # if rememberme == 'on':
            res.set_cookie('username', username, expires=15*24*60*60)
            res.set_cookie('password', password, expires=15*24*60*60)
            res.set_cookie('rememberme', rememberme, expires=15*24*60*60)
            # else:
            #     # 删除cookie信息
            #     res.delete_cookie('username')
            #     res.delete_cookie('password')
            #     res.delete_cookie('rememberme')
            return res
        else:
            context = {'errorMsg': '密码或用户名错误'}
            print('cookie_username', req.COOKIES.get('username'))
            return render(req, 'xzb/login.html', context)

def next_reg(req):
    if req.method == 'GET':
        return render(req, 'xzb/next_reg.html')
    elif req.method == 'POST':
        # 获取页面提交的字段
        id = req.POST.get('user_id')
        user = User.objects.get(pk=id)
        user.actorurl = req.FILES.get('resource')
        user.nickname = req.POST.get('nickname')
        realName = req.POST.get('realName')
        birthday = req.POST.get('birth')
        sex = req.POST.get('sex')
        print('sex', sex)
        user.realName = realName
        user.birthday = birthday
        user.gender = True
        user.save()
        total = User.objects.count()
        context = {'nickname': user.nickname, 'total': total}
        # 向用户的注册邮箱发送一个激活超链接：修改用户状态的路由
        user_id = user.id
        href = f'http://127.0.0.1:8000/xzb/activeuser/{user_id}'
        html_message = f"<a href={href}> 请点击链接，激活你的账号"
        print('html_message:', html_message)
        send_mail(
            subject='用户激活，请点击链接激活账号',
            message='尊敬用户你好，请点击以下链接，激活你的账号',
            from_email="17839723419@163.com",
            recipient_list=[user.email],
            fail_silently=False, # 如果设置为True，则在发送邮件过程中遇到错误不会抛出异常
            html_message=html_message
        )
        return render(req, 'xzb/success.html', context)


def success(req):
    return render(req, 'xzb/success.html')


def logout(req):
    # res = render(req, 'xzb/index.html')
    # 清空session
    req.session.clear()
    res = redirect(reverse('xzbindex'))
    # 删除cookie信息
    # res.delete_cookie('username')
    # res.delete_cookie('password')
    return res


def test(request):
    return render(request,'xzb/test.html')


@require_http_methods(['GET', 'POST'])
def sendmail(request):
    if request.method == 'GET':
        return render(request,'xzb/mail.html')
    elif request.method == 'POST':
        subject = request.POST.get('subject')
        recives = request.POST.get('recives')
        recipient_list = recives.split(',')
        message = request.POST.get('message')
        # 编写发送邮件的代码
        print('开始发送邮件')
        send_mail(
            subject=subject,
            message=message,
            from_email="17839723419@163.com",
            recipient_list=recipient_list,
            fail_silently=False  # 如果设置为True，则在发送邮件过程中遇到错误不会抛出异常
        )
        return HttpResponse("邮件发送成功")
def activeuser(request, id):
    # 根据用户id获取当前用户对象，然后在修改用户的审核状态，登录页面
    user = User.objects.get(pk=id)
    if user:
        # 更新用户状态
        user.status = 1
        user.save()
        context = {'success':'激活成功,请登录！'}
        return render(request,'xzb/login.html', context)
    else:
        return render(request, 'xzb/index.html')


def findpass(request):
    if request.method == 'GET':
        return render(request, 'xzb/findpass.html')
    elif request.method == 'POST':
        # 找回密码
        username = request.POST.get('username')
        email = request.POST.get('email')
        user = User.objects.filter((Q(userName__iexact=username) & Q(email__iexact=email) & Q(status__iexact=1)))
        if len(user) == 1:
            password = user[0].password
            # 发送邮件
            send_mail(
                subject='找回密码',
                message=f'尊敬的用户你好：你的密码已找回，密码是：{password},请注意保管，或尽快修改密码！',
                from_email="17839723419@163.com",
                recipient_list=[email],
                fail_silently=False  # 如果设置为True，则在发送邮件过程中遇到错误不会抛出异常
            )
            context = {"success": '你的密码已找回,请重新登录'}
            return render(request, 'xzb/login.html', context)
        else:
            context = {'errorMsg': '你的用户名或电子邮件错误！'}
            return render(request, 'xzb/login.html', context)


# @checklogin
def personal(request):
    if request.method == 'GET':
        return render(request, 'xzb/personal.html')


def modifypass(request):
    if request.method == 'GET':
        return render(request, 'xzb/modifypass.html')
    else:
        # 获取密码信息，必须有用户信息：从session中获取用户信息，然后在判断修改
        username = request.POST.get('username')
        oldpassword = request.POST.get('oldpassword')
        newpassword = request.POST.get('password')
        enterpassword = request.POST.get('enterpassword')
        print(newpassword, enterpassword)
        user = User.objects.get(userName=username)
        if user:
            password = user.password
            if password != oldpassword:
                context = {'errorMsg': '原密码错误！'}
                return render(request, 'xzb/modifypass.html', context)
            elif newpassword != enterpassword:
                context = {'errorMsg': '新密码和确认密码不一致！'}
                return render(request, 'xzb/modifypass.html', context)
            else:
                # 修改密码
                user.password = newpassword
                user.save()
                # context = {"success": '密码修改成功，请重新登录'}
                res = redirect(reverse('xzblogin'))
                res.delete_cookie('username')
                res.delete_cookie('password')
                res.delete_cookie('rememberme')
                return res
        else:
            context = {'errorMsg': '修改错误，请与管理员联系！'}
            return render(request, 'xzb/modifypass.html', context)


def bbs(request):
    return render(request, 'xzb/bbs.html')


def attention(request):
    return render(request, 'xzb/attention.html')


def message(request):
    if request.method == 'GET':
        official = Notice.objects.filter(Type=1)
        notice = Notice.objects.filter(Type=2)
        context = {
            'official': official,
            'notice': notice,
            'official_count': official.count(),
            'notice_count': notice.count()
        }
        return render(request, 'xzb/message.html', context)
    elif request.method == 'POST':
        r = Notice()
        r.Userid = request.POST.get('Userid')
        r.Type = request.POST.get('Type')
        r.Noticetype = request.POST.get('Noticetype')
        r.Content = request.POST.get('Content')
        r.save()
        official = Notice.objects.filter(Type=1)
        notice = Notice.objects.filter(Type=2)
        context = {
            'official': official,
            'notice': notice,
            'official_count': official.count(),
            'notice_count': notice.count()
        }
        return render(request, 'xzb/message.html', context)


def chat(req):
    value = False
    user = User.objects.all()
    content = {'users': user, 'value': value}
    return render(req, 'xzb/chat.html', content)


def chats(request, id):
    if request.method == 'GET':
        users = User.objects.all()
        user1 = User.objects.get(pk=id)
        user2_name = request.session.get('username')
        user2 = User.objects.get(userName=user2_name)
        pls = Private_letter.objects.all()
        plist = []
        # plists = []
        # 获取私信并按时间排序
        for pl in pls:
            if pl.Userid == user1.id and pl.Contactid == user2.id:
                plist.append(pl)
            if pl.Userid == user2.id and pl.Contactid == user1.id:
                plist.append(pl)
        value = True

        return render(request, 'xzb/chat.html', locals())


def send(request, id):
    username = request.session.get('username')
    user2 = User.objects.get(userName=username)
    pl = Private_letter()
    pl.Userid = user2.id
    pl.Contactid = id
    pl.Message = request.POST.get('message')
    pl.Create_time = datetime.now()
    pl.Update_time = datetime.now()
    pl.save()
    return redirect(reverse('xzbchat'))





def blacklist(request):
    if request.method == 'GET':
        # 获取当前用户的黑名单
        user_id = request.user.id
        black_list = Black_user.objects.filter(Userid=user_id)
        context = {
            'black_list': black_list,
        }
        return render(request, 'xzb/message.html', context)
    elif request.method == 'POST':
        user_id = request.POST.get('Userid')
        black_user_id = request.POST.get('Blackuserid')
        if 'add' in request.POST:  # 添加黑名单
            r = Black_user()
            r.Userid = user_id
            r.Blackuserid = black_user_id
            r.save()
        elif 'remove' in request.POST:  # 解除黑名单
            Black_user.objects.filter(Userid=user_id, Blackuserid=black_user_id).delete()
        return redirect('message')


def detail(request):

    return render(request, 'xzb/detail.html')





